<template>
  <div class="text-box">
    <van-form>
      <!-- 富文本编辑器 -->
      <quill-editor v-model="content" :options="editorOption" @change="onEditorChange($event)" ref="textEd"> </quill-editor>
      <van-field name="uploader">
        <template #input>
          <van-uploader v-model="fileList" ref="uploader" accept=".png,.jpg,.jpeg" :before-read="beforeRead" :after-read="afterRead" :before-delete="deleteFn" multiple :max-count="3" />
        </template>
      </van-field>
      <!-- 日记天气/字数/地址详情 -->
      <div class="details">
        <!-- 天气 -->
        <span v-if="nowweartherShow">
          <i :class="'qi-' + this.nowicon"></i>
          <p>{{ nowwearther }}&nbsp;·&nbsp;{{ temperature }}℃</p>
        </span>
        <span v-else>
          <van-loading />
        </span>
        <!-- 地址· -->
        <span v-if="nowCityNameShow">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-dingwei"></use>
          </svg>
          <p>{{ nowCityName }}</p>
        </span>
        <span v-else>
          <van-loading />
        </span>
        <!-- 文字 -->
        <span>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-zitiyulan"></use>
          </svg>
          <!-- <p>16 字</p> -->
          <p>{{ TiLength }} 字</p>
        </span>
      </div>
      <!-- 编辑天气弹出层 -->
      <!-- <van-action-sheet v-model="weathershow" title="切换天气">
        <div class="content">
          <span v-for="item in weatherIcon" :key="item.id" @click="getweatherIcon(item.id,item.text)">
            <svg class="icon" aria-hidden="true">
              <use :xlink:href="item.name"></use>
            </svg>
            <p >{{ item.text }}</p>
          </span>
        </div>
      </van-action-sheet> -->
    </van-form>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import axios from 'axios'
import { Toast } from 'vant'
// import e from 'express'

// import BMap from 'bmap'

// 工具栏配置
const toolbarOptions = [
  // [{ list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  // [{ indent: '-1' }, { indent: '+1' }] // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
]

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      content: '', // 富文本编辑器默认内容
      editorOption: {
        //  富文本编辑器配置
        modules: {
          // 工具栏定义的
          toolbar: toolbarOptions,
          clipboard: {
            // 粘贴过滤
            matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]]
          }
        },
        // 主题
        theme: 'snow',
        placeholder: ' 时光荏苒 记录今日...'
      },
      // 上传图片
      fileList: [],
      // 压缩上传图片的base64
      imgurl: [],
      // 天气弹出层
      // weathershow: false,
      // // 天气选项数据
      // weatherIcon: [
      //   {
      //     name: '#icon-qing-xian',
      //     id: 1,
      //     text: '晴'
      //   },
      //   {
      //     name: '#icon-icon--',
      //     id: 2,
      //     text: '雾霾'
      //   },
      //   {
      //     name: '#icon-baitian-bingbao',
      //     id: 3,
      //     text: '冰雹'
      //   },
      //   {
      //     name: '#icon-dafeng',
      //     id: 4,
      //     text: '大风'
      //   },

      //   {
      //     name: '#icon-leizhenyu',
      //     id: 5,
      //     text: '雷雨'
      //   },
      //   {
      //     name: '#icon-tianqiqingzhuanduoyunyewan',
      //     id: 6,
      //     text: '深夜'
      //   },
      //   {
      //     name: '#icon-sunsetrila',
      //     id: 7,
      //     text: '日落'
      //   },
      //   {
      //     name: '#icon-richu-04',
      //     id: 8,
      //     text: '日出'
      //   },
      //   {
      //     name: '#icon-yin-xian',
      //     id: 9,
      //     text: '阴天'
      //   },
      //   {
      //     name: '#icon-zhongyu-xian',
      //     id: 10,
      //     text: '雨'
      //   },
      //   {
      //     name: '#icon-wu-xian',
      //     id: 11,
      //     text: '雾'
      //   },
      //   {
      //     name: '#icon-qingzhuanduoyun-xian',
      //     id: 12,
      //     text: '多云'
      //   },
      //   {
      //     name: '#icon-zhongxue-xian',
      //     id: 13,
      //     text: '雪'
      //   },
      //   {
      //     name: '#icon-shachenbao',
      //     id: 14,
      //     text: '沙尘暴'
      //   }
      // ],
      // 点击的天气
      newWeatherIcon: '',
      // 当前城市
      nowCityName: '',
      // 城市纬度
      lng: '',
      // 城市经度
      lat: '',
      // 当前城市的天气
      nowwearther: '',
      // 当前城市的天气图标
      nowicon: '',
      // 当前城市的温度
      temperature: '',
      // 文章字数
      TiLength: 0,
      // 天气 加载中 显示
      nowweartherShow: false,
      // 城市 加载中 显示
      nowCityNameShow: false
    }
  },

  methods: {
    // 过滤 复制粘贴 的数据
    HandleCustomMatcher (node, Delta) {
      // 文字、图片等，从别处复制而来，清除自带样式，转为纯文本
      const ops = []
      Delta.ops.forEach(op => {
        if (op.insert && typeof op.insert === 'string') {
          ops.push({
            insert: op.insert
          })
        }
      })
      Delta.ops = ops
      return Delta
    },

    // 获取城市
    getcityname () {
      try {
        new BMap.LocalCity().get((res) => {
          this.nowCityName = res.name // 城市名称
          this.lng = res.center.lng + '' // 城市经度
          this.lat = res.center.lat + '' // 城市纬度
          // console.log(this.lng, this.lat)
          this.nowCityNameShow = true
        })
      } catch (error) {
        this.nowCityName = '获取城市失败' // 城市名称
        this.nowCityNameShow = true
      }
    },

    // 获取城市天气
    async getweatherDate () {
      try {
        // const result = await axios.get('http://devapi.qweather.com/v7/weather/now?location=' + this.lng + ',' + this.lat + '&key=db25a172c17f41aa8fb876eea292bed8')
        const result = await axios({
          url: 'https://devapi.qweather.com/v7/weather/now?location=' + this.lng + ',' + this.lat + '&key=db25a172c17f41aa8fb876eea292bed8',
          method: 'get',
          timeout: 8000
        })
        // console.log(result)
        // console.log(result.data.code === '400')
        if (result.data.code === '400') {
          this.nowwearther = '获取天气失败'
          this.temperature = '获取温度失败'
          this.nowicon = '100'
          this.nowweartherShow = true
        } else {
          this.nowwearther = result.data.now.text
          this.temperature = result.data.now.temp
          this.nowicon = result.data.now.icon
          // console.log(this.nowicon)
          this.nowweartherShow = true
        } // console.log('https://devapi.qweather.com/v7/weather/now?location=' + this.lng + ',' + this.lat + '&key=db25a172c17f41aa8fb876eea292bed8')
      } catch (error) {
        this.nowwearther = '获取天气失败'
        this.temperature = '获取温度失败'
        this.nowicon = '100'
        this.nowweartherShow = true
      }
    },
    // 富文本内容改变事件
    onEditorChange (e) {
      // 计算 富文本内容 字数
      e.quill.deleteText(800, 4)
      // console.log(e)
      if (this.content === '') {
        this.TiLength = 0
      } else {
        this.TiLength = e.quill.getLength() - 1
      }
      // this.content = e.text
      // console.log(this.content)
    },
    // 限制上传图片的大小
    // onOversize () {
    //   Toast('图片大小不能超过 500kb')
    // },
    // 图片压缩处理函数
    compressImg (base64String, w, quality) {
      // 计算占多少 bytes
      function getBytesLength (str) {
        let num = str.length // 先用num保存一下字符串的长度（可以理解为：先假设每个字符都只占用一个字节）
        for (let i = 0; i < str.length; i++) {
          // 遍历字符串
          if (str.charCodeAt(i) > 255) {
            // 判断某个字符是否占用两个字节，如果是，num再+1
            num++
          }
        }
        return num // 返回最终的num，既是字符串总的字节长度
      }
      const base64Length = getBytesLength(base64String)
      // 计算占 多少 kb
      const size = base64Length / 1024

      // 判断图片是否小于 250kb  => 小于就不用压缩
      if (size < 200) {
        return base64String
      }
      // 判断图片 大于 250kb  => 压缩 图片
      const getMimeType = function (urlData) {
        const arr = urlData.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        return mime
      }
      const newImage = new Image()
      let imgWidth, imgHeight

      const promise = new Promise((resolve) => (newImage.onload = resolve))
      newImage.src = base64String
      return promise.then(() => {
        imgWidth = newImage.width
        imgHeight = newImage.height
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w
            canvas.height = (w * imgHeight) / imgWidth
          } else {
            canvas.height = w
            canvas.width = (w * imgWidth) / imgHeight
          }
        } else {
          canvas.width = imgWidth
          canvas.height = imgHeight
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height)
        const base64 = canvas.toDataURL(getMimeType(base64String), quality)
        // console.log(base64)
        return base64
      })
    },

    // 上传图片之前钩子
    beforeRead (file) {
      // 一次上传单张, file 为对象 => 循环判断 file  是否为 合法格式图片
      if (!Array.isArray(file)) {
        if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file.type)) {
          Toast('亲~只能上传jpg|jpeg|png|JPG|PNG图片格式噢')
          // console.log(file.type)
          return false
        }
        // console.log(file.content)
        // this.repeatImgs = 0
      } else {
        // 一次上传多张，file是一个数组 => 循环判断 file 数组 每一项 是否为 合法格式图片
        for (let i = 0; i < file.length; i++) {
          if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file[i].type)) {
            Toast('亲~只能上传jpg|jpeg|png|JPG|PNG图片格式噢')
            // console.log(file.type)
            return false
          }
          // console.log(file[i])
        }
        // this.repeatImgs = 0
      }
      return true
    },
    // 上传图片成功的钩子
    async afterRead (file) {
      // console.log(this.fileList)
      const arr1 = this.fileList.map(async (item, index) => {
        // console.log(this.fileList[index].content)
        // console.log();
        // 调用图片压缩处理函数 压缩图片
        const baseImg = await this.compressImg(this.fileList[index].content, 500, 0.7)
        // console.log(baseImg)
        return baseImg
      })
      const base64 = await Promise.all(arr1)
      this.imgurl = base64.join('||')
      // console.log(this.imgurl)

      this.$store.commit('setArticleImg', this.imgurl)
      // console.log(this.fileList)
    },
    // 删除图片
    async deleteFn (file, detail) {
      const arr1 = this.fileList.map(async (item, index) => {
        // console.log(this.fileList[index].content)
        // console.log();
        // 调用图片压缩处理函数 压缩图片
        const baseImg = await this.compressImg(this.fileList[index].content, 500, 0.7)
        // console.log(baseImg)
        return baseImg
      })
      const base64 = await Promise.all(arr1)
      this.imgurl = base64.join('||')
      // console.log(this.imgurl)
      // this.imgurl.splice(detail.index, 1)
      this.fileList = this.fileList.splice(detail.index, 1)

      this.$store.commit('setArticleImg', this.imgurl)
      // console.log(this.fileList)
    },
    // 退出编辑清空日记数据
    emptyFn () {
      // console.log('清空日记数据')
      this.fileList = []
      this.imgurl = []
      this.$store.commit('setArticleImg', this.imgurl)
      this.content = ''
    }
  },

  created () {
    this.getcityname()
    setTimeout(() => {
      this.getweatherDate()
    }, 1500)
    // this.$nextTick(() => {
    //   console.log(this.$refs.textEd.quill.selection)
    // })
    // quill.setSelection(this.content.length, this.content.length)
  },
  updated () {
    this.$store.commit('setArticleData', [this.content, this.nowCityName, this.nowwearther, this.nowicon, this.temperature, this.TiLength])
  }
}
</script>

<style lang="less">
.editor {
  line-height: normal !important;
  height: 500px;
}
.ql-editor {
  min-height: 220px;
  // max-height: 550px;
  padding: 60px 28px;
}
.ql-toolbar.ql-snow {
  border: 0;
}
.ql-editor.ql-blank::before {
  color: #969799;
  font-style: normal;
  padding: 0 6px;
}
.ql-editor p {
  color: #646566;
  font-size: 14px;
  letter-spacing: 2px;
  line-height: 22px;
  // white-space: pre-wrap;
}
.ql-toolbar.ql-snow {
  border: 0;
}
.ql-container.ql-snow {
  border: 0;
}
.van-uploader__wrapper {
  padding-left: 12px;
}
.van-uploader__upload {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: #ebedf0;
  .van-uploader__upload-icon {
    color: #6ed9a2;
    font-size: 20px;
  }
}
.van-uploader__preview-image {
  border-radius: 10px;
  width: 100px;
  height: 100px;
}
.van-uploader__preview-delete {
  width: 18px;
  height: 18px;
  background-color: #f80000a6;
  border-radius: 50%;
}
.van-uploader__preview-delete-icon {
  top: -2px;
  right: -2px;
  font-size: 22px;
}
.details {
  padding: 5px 28px 20px 28px;

  span {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 10px 0;
    .van-loading {
      width: 20px;
      height: 20px;
    }

    i {
      font-size: 19px;
      color: #969799;
      padding-right: 6px;
    }
    .icon {
      width: 18px;
      height: 18px;
      padding-right: 6px;
      fill: #969799;
    }
    p {
      font-size: 12px;
      color: #969799;
    }
  }
}
.van-action-sheet__header {
  color: #969799;
}
// .content {
//   padding: 0 16px 80px;
//   display: flex;
//   flex-wrap: wrap;
//   justify-content: center;
//   span {
//     padding: 10px 26px;
//     display: flex;
//     flex-direction: column;
//     align-items: center;
//     .icon {
//       width: 32px;
//       height: 32px;
//     }
//     p {
//       font-size: 15px;
//       padding: 5px 0;
//       color: #969799;
//     }
//   }
// }
</style>
